/*
 * 全局声明一个ws客户端实例
 * 开发者可以根据自己的需求，调整该页面代码(这是个模板)
 * @Author: bobo
 * @Date: 2021-01-11 13:45:08
 */
import WsClient from '@/ws/WsClient'


const url = 'ws://127.0.0.1:9800';
const opts = {
  //配置自动重连相关参数
  autoReconnection: true,
  minReconnectionDelay: 5000,
  maxReconnectionDelay: 60000,
  reconnectionStep: 2000,
};
//最大心跳数
const maxHeartCount = 3;
export const PING = {
  prt: "20000",
  cmd: "ping",
  dev: "test123456",
};

var pingIntervalID = 0;
var heartCount = 0;

function startHeartBeat(cli) {
  clearInterval(pingIntervalID)
  heartCount = 0;
  pingIntervalID = setInterval(function () {
    if (heartCount >= maxHeartCount) {
      //连接断开
      cli.reconnect();
      return;
    }
    let _ping = JSON.stringify(PING);
    console.log("发送心跳,第" + heartCount + "次")
    cli.sendMessage(_ping)
    heartCount++;
  }, 10000);
}

function isPong(data) {
  return 'pong' == JSON.parse(data).cmd
}
var ws = null;
export default {
  /**
   * 创建客户端
   * @param  vm Vue实例 
   */
  createWebSocket(vm) {
    this.closeWebSocket(vm);
    ws = new WsClient(url, opts);
    ws.connect({
      onOpen: function (success) {
        console.log("WS连接建立结果:" + success + "#" + ws.state())
        vm.$emit("ws-onOpen", success)
        startHeartBeat(ws)
      },
      onMessage: function (data) {
        console.log(data)
        heartCount = 0;
        if (!isPong(data)) {
          vm.$emit("ws-onMessage", data)
        }
      },
      onReconning(count, nextDelay) {
        console.log('第' + count + "重连,若失败，下次时间间隔:" + nextDelay)
        vm.$emit("ws-onReconning", count, nextDelay)
      },
      onClosed: function (code, reason) {
        console.log(code + "#" + reason)
        vm.$emit('ws-onClosed', code, reason)
      },
      onFaile: function (code, msg) {
        console.log(code + "#" + msg)
        vm.$emit('ws-onFaile', code, msg)
      },
      onManualClose: function () {
        console.log('手动关闭websocket')
        clearInterval(pingIntervalID)
      }
    })
  },
  sendMessage(data) {
    if (ws) {
      ws.sendMessage(JSON.stringify(data));
    }
  },
  closeWebSocket() {
    if (ws) {
      ws.close();
      ws = null;
    }
  }
}